<template>
	<view class="detail-page">
		<!-- 左侧固定业务类型导航 -->
		<view class="side-nav">
			<view class="side-nav-item" :class="{ active: activeBusinessType === 'outbound' }" @click="switchBusinessType('outbound')"><text>销\n售</text></view>
			<view class="side-nav-item" :class="{ active: activeBusinessType === 'purchase' }" @click="switchBusinessType('purchase')"><text>进\n货</text></view>
			<!-- <view class="side-nav-item" :class="{ active: activeBusinessType === 'payment' }" @click="switchBusinessType('payment')"><text>收\n款</text></view>
			<view class="side-nav-item" :class="{ active: activeBusinessType === 'fund' }" @click="switchBusinessType('fund')"><text>资\n金</text></view>
			<view class="side-nav-item" :class="{ active: activeBusinessType === 'inventory' }" @click="switchBusinessType('inventory')"><text>盘\n点</text></view> -->
		</view>

		<!-- 顶部时间标签 (现在直接在 detail-page 下) -->
		<view class="date-tabs">
			<view class="date-tab-item" :class="{ active: activeTab === 'custom' }" @click="switchTab('custom')"><text>自定义</text></view>
			<view class="date-tab-item" :class="{ active: activeTab === 'week' }" @click="switchTab('week')"><text>本周</text></view>
			<view class="date-tab-item" :class="{ active: activeTab === 'today' }" @click="switchTab('today')"><text>今日</text></view>
			<view class="date-tab-item" :class="{ active: activeTab === 'thisMonth' }" @click="switchTab('thisMonth')"><text>本月</text></view>
			<view class="date-tab-item" :class="{ active: activeTab === 'thisYear' }" @click="switchTab('thisYear')"><text>本年</text></view>
		</view>
		
		<!-- 新的内容区域容器 -->
		<view class="content-area">
			<!-- 主内容区域 (现在只包含 content-panel) -->
			<view class="main-content">
				<!-- 内容面板 -->
				<view class="content-panel">
					<!-- 动态业务类型子菜单 -->
					<view class="business-type-tabs" v-if="activeBusinessType === 'outbound'">
						<view class="business-type-tab" :class="{ active: activeSalesSubType === 'outbound' }" @click="switchSalesSubType('outbound')"><text>出货</text></view>
						<view class="business-type-tab" :class="{ active: activeSalesSubType === 'returned' }" @click="switchSalesSubType('returned')"><text>退货</text></view>
						<view class="business-type-tab" :class="{ active: activeSalesSubType === 'payment' }" @click="switchSalesSubType('payment')"><text>收款</text></view>
					</view>
					<view class="business-type-tabs" v-if="activeBusinessType === 'purchase'">
						<view class="business-type-tab" :class="{ active: activePurchaseSubType === 'purchase' }" @click="switchPurchaseSubType('purchase')"><text>进货单</text></view>
						<view class="business-type-tab" :class="{ active: activePurchaseSubType === 'purchase_return' }" @click="switchPurchaseSubType('purchase_return')"><text>退货单</text></view>
						<view class="business-type-tab" :class="{ active: activePurchaseSubType === 'purchase_payment' }" @click="switchPurchaseSubType('purchase_payment')"><text>付款单</text></view>
					</view>
					<view class="business-type-tabs" v-if="activeBusinessType === 'fund'">
						<view class="business-type-tab" :class="{ active: activeFundSubType === 'income' }" @click="switchFundSubType('income')"><text>收入单</text></view>
						<view class="business-type-tab" :class="{ active: activeFundSubType === 'expense' }" @click="switchFundSubType('expense')"><text>支出单</text></view>
					</view>
					<!-- 收款和盘点无顶部菜单 -->
					<view v-if="activeBusinessType === 'payment' || activeBusinessType === 'inventory'" class="no-sub-tabs-placeholder"></view>
					
					<!-- 搜索框 -->
					<view class="search-box">
						<view class="search-input-wrapper">
							<u-icon name="search" size="28" color="#AEAEAE"></u-icon>
							<input 
								type="text" 
								:placeholder="searchPlaceholder"
								placeholder-style="color: #AEAEAE;"
								v-model="searchKeyword" 
								@input="handleSearch"
							/>
							<view class="clear-icon" v-if="searchKeyword" @click="clearSearch">
								<u-icon name="close-circle-fill" size="24" color="#BFBFBF"></u-icon>
							</view>
						</view>
					</view>
					
					<!-- 日期和合计 -->
					<view class="date-total-bar">
						<text class="date-range">{{ formatDateRange }}</text>
						<view class="total-section">
							<text class="total-label">合计：</text>
							<text class="total-amount">¥{{ totalAmount.toFixed(2) }}</text>
						</view>
						<!-- Conditionally render the add button -->
						<view class="add-button" @click="addNewRecord" v-if="activeBusinessType !== 'payment' && activeBusinessType !== 'inventory'">
							<u-icon name="plus" color="#FFFFFF"></u-icon>
						</view>
					</view>
					
					<!-- 明细列表 -->
					<view class="detail-list-container">
						<scroll-view 
							scroll-y 
							class="detail-list-scroll" 
							@scrolltolower="handleScrollToLower"
							v-if="detailList.length > 0"
						>
							<view class="detail-item" v-for="(item, index) in detailList" :key="index" @click="viewDetail(item)">
								<view class="item-info">
									<view class="info-line-1">
										<text class="item-date">{{ item.date }}</text>
										<text class="item-amount">¥ {{item.type==="receiveOrder"||item.type==="paymentOrder"?item.money:item.discountedAmount}}</text>
									</view>
									<view class="info-line-2">
										<text class="item-customer">{{ item.customerName }}</text>
									</view>
									<view class="info-line-3">
										<text class="item-code">{{ item.code }}</text>
									</view>
								</view>
								<u-icon name="arrow-right" color="#D8D8D8" size="24" class="arrow-icon"></u-icon>
							</view>
							
							<view class="loadmore-area">
								<u-loadmore :status="loadStatus" />
							</view>
						</scroll-view>
						
						<!-- 空状态 -->
						<view class="empty-state" v-if="detailList.length === 0 && !loading">
							<image src="/static/images/empty-illustration.png" mode="aspectFit" class="empty-image"></image>
							<text class="empty-text">当前时间段内您还未产生过订单数据</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/utils/api.js';
	
	export default {
		data() {
			return {
				activeTab: 'thisMonth',
				activeBusinessType: 'outbound', // Main type from side nav
				activeSalesSubType: 'outbound', // Sub type for Sales
				activePurchaseSubType: 'purchase', // Sub type for Purchase
				activeFundSubType: 'income', // Sub type for Fund
				searchKeyword: '',
				startDate: '',
				endDate: '',
				detailList: [],
				totalAmount: 0.00,
				loading: false,
				page: 1,
				limit: 20,
				hasMore: true,
				loadStatus: 'loadmore', // loadmore, loading, nomore
				customerMap: {}, // 新增：客户ID到名称的映射
				supplierMap: {} // 新增：供应商ID到名称的映射
			}
		},
		computed: {
			formatDateRange() {
				if (!this.startDate || !this.endDate) return '';
				if (this.startDate === this.endDate) {
					return this.startDate;
				}
				return `${this.startDate}~${this.endDate}`;
			},
			// 根据当前类型决定API请求参数和type类型
			currentApiType() {
				let apiType = '';
				let orderType = '';

				// 根据当前业务类型和子类型确定接口类型和订单类型
				switch (this.activeBusinessType) {
					case 'outbound': // 销售类型
						if (this.activeSalesSubType === 'outbound') { 
							apiType = 'sales';        // API类型是销售接口
							orderType = 'salesOrder'; // 订单类型是出货单
						} else if (this.activeSalesSubType === 'returned') {
							apiType = 'sales';        // API类型同样是销售接口
							orderType = 'returnOrder'; // 订单类型是退货单
						} else if (this.activeSalesSubType === 'payment') {
							apiType = 'sales';         // API类型同样是销售接口
							orderType = 'receiveOrder'; // 订单类型是收款单
						}
						break;
					case 'purchase': // 进货类型
						if (this.activePurchaseSubType === 'purchase') {
							apiType = 'purchase';      // API类型是进货接口
							orderType = 'purchaseOrder'; // 订单类型是进货单
						} else if (this.activePurchaseSubType === 'purchase_return') {
							apiType = 'purchase';      // API类型同样是进货接口
							orderType = 'returnOrder'; // 订单类型是退货单
						} else if (this.activePurchaseSubType === 'purchase_payment') {
							apiType = 'purchase';      // API类型同样是进货接口
							orderType = 'paymentOrder'; // 订单类型是付款单
						}
						break;
					// 保留其他类型的处理
					default:
						apiType = 'unknown';
						orderType = '';
				}

				// 返回包含API类型和订单类型的对象
				return {
					apiType: apiType,
					orderType: orderType
				};
			},
			// 动态搜索框占位符
			searchPlaceholder() {
				switch (this.activeBusinessType) {
					case 'outbound': return '单据号/客户名称/品名规格/备注';
					case 'purchase': return '单据号/供应商名称/品名规格/备注';
					case 'payment': return '单据号/客户名称/备注';
					case 'fund': return '单据号/往来单位/备注';
					case 'inventory': return '单据号/仓库名称/备注';
					default: return '搜索...';
				}
			},
			// 详情页的基础路径
			currentDetailUrlBase() {
				const apiType = this.currentApiType.apiType;
				
				switch (apiType) {
					case 'sales': return '/pages/sales/detail'; // 销售详情页
					case 'purchase': return '/pages/purchase/detail'; // 进货详情页
					// 保留其他类型的处理
					default: return '';
				}
			}
		},
		created() {
			this.initDateRange();
			this.loadCustomerList(); // 新增：加载客户列表
			this.loadSupplierList(); // 新增：加载供应商列表
		},
		onShow() {
			this.loadDetailList();
		},
		onPullDownRefresh() {
			this.page = 1;
			this.detailList = [];
			this.hasMore = true; // 重置hasMore状态
			this.loadStatus = 'loadmore';
			this.loadDetailList(true);
		},
		methods: {
			initDateRange() {
				const now = new Date();
				const today = this.formatDate(now);
				
				switch (this.activeTab) {
					case 'custom':
						// TODO: Add logic to open date range picker if needed
						if (!this.startDate || !this.endDate) {
							this.activeTab = 'thisMonth'; // Fallback to this month if custom not set
							this.initDateRange(); // Recalculate for this month
						}
						break;
					case 'today':
						this.startDate = today;
						this.endDate = today;
						break;
					case 'week':
						const day = now.getDay() || 7;
						const monday = new Date(now);
						monday.setDate(now.getDate() - day + 1);
						const sunday = new Date(now);
						sunday.setDate(now.getDate() - day + 7);
						this.startDate = this.formatDate(monday);
						this.endDate = this.formatDate(sunday);
						break;
					case 'thisMonth':
						const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
						const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
						this.startDate = this.formatDate(firstDay);
						this.endDate = this.formatDate(lastDay);
						break;
					case 'thisYear':
						const firstDayOfYear = new Date(now.getFullYear(), 0, 1);
						const lastDayOfYear = new Date(now.getFullYear(), 11, 31);
						this.startDate = this.formatDate(firstDayOfYear);
						this.endDate = this.formatDate(lastDayOfYear);
						break;
				}
			},
			
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			
			switchTab(tab) {
				if (this.activeTab === tab) return;
				this.activeTab = tab;
				this.initDateRange();
				this.resetAndLoad();
			},
			
			switchBusinessType(type) {
				if (this.activeBusinessType === type) return;
				this.activeBusinessType = type;
				// Reset sub-types to default
				this.activeSalesSubType = 'outbound';
				this.activePurchaseSubType = 'purchase';
				this.activeFundSubType = 'income';
				this.resetAndLoad();
			},

			switchSalesSubType(type) {
				if (this.activeSalesSubType === type) return;
				this.activeSalesSubType = type;
				this.resetAndLoad();
			},

			switchPurchaseSubType(type) {
				if (this.activePurchaseSubType === type) return;
				this.activePurchaseSubType = type;
				this.resetAndLoad();
			},

			switchFundSubType(type) {
				if (this.activeFundSubType === type) return;
				this.activeFundSubType = type;
				this.resetAndLoad();
			},
			
			handleSearch() {
				// Add debounce later if needed
				this.resetAndLoad();
			},
			
			clearSearch() {
				this.searchKeyword = '';
				this.resetAndLoad();
			},

			resetAndLoad() {
				this.page = 1;
				this.detailList = [];
				this.hasMore = true; // Assume there might be more on new load
				this.loadStatus = 'loadmore';
				this.loadDetailList();
			},
			
			loadDetailList(isPullDown = false) {
				if (this.loading) return;
				this.loading = true;
				this.loadStatus = 'loading';
				
				// 获取当前API类型和订单类型
				const currentType = this.currentApiType;
				const apiType = currentType.apiType;
				const orderType = currentType.orderType;
				
				const params = {
					pageNum: this.page,
					pageSize: this.limit,
					beginTime: this.startDate,
					endTime: this.endDate,
					type: orderType, // 使用订单类型作为type参数
					keyword: this.searchKeyword
				};
				
				console.log('Request Params:', params);
				console.log('Current API Type:', apiType, 'Order Type:', orderType);

				let apiCallPromise;

				// 根据API类型调用相应的接口
				switch (apiType) {
					case 'sales': // 销售相关接口
						if (api.listSales) {
							apiCallPromise = api.listSales(params);
						} else {
							console.error('API函数api.listSales未定义');
							apiCallPromise = Promise.reject('API函数未定义');
						}
						break;
					case 'purchase': // 进货相关接口
						if (api.listPurchase) {
							apiCallPromise = api.listPurchase(params);
						} else {
							console.error('API函数api.listPurchase未定义');
							apiCallPromise = Promise.reject('API函数未定义');
						}
						break;
					// 保留其他API类型的处理逻辑
					default:
						console.error('Unknown API type:', apiType);
						apiCallPromise = Promise.reject('Unknown API type');
						break;
				}

				apiCallPromise.then(res => {
					// 处理响应数据的逻辑保持不变
					if (isPullDown) {
						uni.stopPullDownRefresh();
					}
					this.loading = false;
					if (res && res.rows && Array.isArray(res.rows)) {
						console.log('API响应数据:', JSON.stringify(res.rows[0])); // 打印第一条记录以便查看结构
						const formattedData = res.rows.map(item => {
							// 更灵活地处理进货单的供应商ID
							let partnerId = null;
							if (apiType === 'purchase') {
								// 优先级：supplierId > customerId > id
								partnerId = item.supplierId !== undefined ? item.supplierId : 
										   (item.customerId !== undefined ? item.customerId : item.id);
								console.log(`进货单记录，供应商ID=${partnerId}，来源字段=${item.supplierId !== undefined ? 'supplierId' : (item.customerId !== undefined ? 'customerId' : 'id')}`);
							} else {
								// 销售单使用customerId
								partnerId = item.customerId;
							}
							
							return {
								id: item.id,
								date:  item.businessDate ||item.createTime || item.date, // 增加businessDate作为日期来源
								customerId: partnerId, // 统一使用customerId存储，无论是客户还是供应商
								customerName: partnerId, // 初始值设为ID，后续替换
								code: item.receiptCode || item.code, // 增加code作为备选
								discountedAmount: item.discountedAmount || item.totalAmount || 0, // 增加totalAmount作为备选
								amount: parseFloat(item.totalAmount || 0).toFixed(2),
								money:item.alipayAmount+item.wechatAmount + item.cashAmount +item.bankAmount
							};
						});
						
						console.log('格式化后的数据:', formattedData);
						
						if (this.page === 1) {
							this.detailList = formattedData;
						} else {
							this.detailList = [...this.detailList, ...formattedData];
						}
						
						// 根据业务类型更新客户/供应商名称
						if (apiType === 'sales') {
							this.updateCustomerNames(); // 销售单更新客户名称
						} else if (apiType === 'purchase') {
							this.updateSupplierNames(); // 进货单更新供应商名称
						}
						
						this.calculateTotalAmount();
						this.hasMore = this.detailList.length < res.total;
						this.loadStatus = this.hasMore ? 'loadmore' : 'nomore';
					} else {
						if (this.page === 1) {
							this.detailList = [];
							this.totalAmount = 0;
						}
						this.hasMore = false;
						this.loadStatus = 'nomore';
					}
				}).catch(err => {
					console.error('获取明细列表失败:', err);
					this.loading = false;
					this.loadStatus = 'loadmore'; // Allow retry on error
					if (isPullDown) {
						uni.stopPullDownRefresh();
					}
					uni.showToast({
						title: '获取明细列表失败',
						icon: 'none'
					});
				});
			},

			// --- MOCK DATA GENERATION --- Remove later
			generateMockData(params) {
				const totalRecords = 50; // Total mock records
				const rows = [];
				const start = (params.pageNum - 1) * params.pageSize;
				const end = start + params.pageSize;

				for (let i = start; i < end && i < totalRecords; i++) {
					const typePrefix = params.type.substring(0, 3).toUpperCase();
					rows.push({
						id: i + 1,
						date: `2025-04-${String(10 + (i % 20)).padStart(2, '0')}`,
						customerName: `${params.type} 客户 ${i + 1}`,
						code: `${typePrefix}${String(202504000000 + i + 1)}.OL`,
						amount: (Math.random() * 1000).toFixed(2)
					});
				}
				return { rows, total: totalRecords };
			},
			// --- END MOCK DATA ---
			
			calculateTotalAmount() {
				// 理想情况下，应该从API获取或基于所有记录计算，
				// 而不仅仅是当前加载的页面。
				// 目前，为了演示，基于已加载列表计算。
				this.totalAmount = this.detailList.reduce((total, item) => {
					return total + parseFloat(item.discountedAmount || 0);
				}, 0);
			},
			
			viewDetail(item) {
				// 获取当前API类型和订单类型
				const currentType = this.currentApiType;
				const apiType = currentType.apiType;
				const orderType = currentType.orderType;
				
				// 根据不同的API类型和订单类型决定跳转逻辑
				if (apiType === 'sales') {
					// 特殊处理收款单
					if (orderType === 'receiveOrder') {
						// 收款单跳转到收款详情页
						uni.navigateTo({ url: `/subPack/payment/detail?id=${item.id}&type=${orderType}` });
					} else {
						// 其他销售类型统一跳转到销售详情页
						uni.navigateTo({ url: `/pages/sales/detail?id=${item.id}&type=${orderType}` });
					}
				} else if (apiType === 'purchase') {
					if(orderType==="paymentOrder"){
						// 付款单跳转到付款详情页
						uni.navigateTo({ url: `/pages/receive/detail?id=${item.id}&type=${orderType}` });
					}else{
						// 进货类型统一跳转到进货详情页
						uni.navigateTo({ url: `/pages/purchase/detail?id=${item.id}&type=${orderType}` });
					}
				} else {
					// 其他类型可能的处理逻辑
					console.warn('Cannot determine detail URL for', apiType, orderType);
					uni.showToast({ title: '无法查看详情', icon: 'none' });
				}
			},
			
			addNewRecord() {
				let targetPath = '';
				let targetTabIndex = null;

				switch (this.activeBusinessType) {
					case 'outbound': // 销售下的所有子类型都跳到开单页的销售Tab
						targetPath = '/pages/order/order';
						targetTabIndex = 0; // 销售 Tab 索引
						break;
					case 'purchase': // 进货下的所有子类型都跳到开单页的进货Tab
						targetPath = '/pages/order/order';
						targetTabIndex = 1; // 进货 Tab 索引
						break;
					case 'fund': // 资金下的子类型跳到开单页
						targetPath = '/pages/order/order';
						if (this.activeFundSubType === 'income') {
							targetTabIndex = 2; // 其他收入 Tab 索引
						} else if (this.activeFundSubType === 'expense') {
							targetTabIndex = 3; // 其他支出 Tab 索引
						} else {
                            // 默认跳到其他收入（或者可以报错）
                            targetTabIndex = 2; 
                        }
						break;
					// case 'inventory': // 盘点按钮已隐藏，但可以预留逻辑
					// 	targetPath = '/pages/inventory/add'; 
					// 	break;
					default:
						console.warn('Cannot determine add URL for', this.activeBusinessType);
						uni.showToast({ title: '无法添加记录', icon: 'none' });
						return; // 阻止后续执行
				}

				if (targetPath === '/pages/order/order' && targetTabIndex !== null) {
					// 跳转到 Tab 页，并设置目标索引
					uni.setStorageSync('targetOrderTabIndex', targetTabIndex);
					uni.switchTab({
						url: targetPath,
                        fail: (err) => {
                            console.error("SwitchTab to order failed from detail:", err);
							uni.removeStorageSync('targetOrderTabIndex'); // 清理失败的标记
                        }
					});
				} else if (targetPath) {
					// 跳转到普通页面
					uni.navigateTo({ url: targetPath });
				}
			},
			
			// 新增方法处理scroll-view的滚动到底部事件
			handleScrollToLower() {
				console.log('滚动到底部，触发加载更多');
				if (this.hasMore && this.loadStatus === 'loadmore') {
					this.page++;
					this.loadStatus = 'loading';
					this.loadDetailList(false);
				}
			},

			// 新增加载客户列表的方法
			loadCustomerList() {
				console.log('加载客户列表...');
				api.listCustomer({ pageNum: 1, pageSize: 1000 })
					.then(res => {
						console.log('客户列表加载成功', res);
						if (res && res.rows && Array.isArray(res.rows)) {
							// 将客户数据转为ID-名称映射
							this.customerMap = {};
							res.rows.forEach(customer => {
								if (customer.id && customer.customerName) {
									this.customerMap[customer.id] = customer.customerName;
								}
							});
							console.log('客户映射表建立完成', this.customerMap);
							
							// 如果已有详情数据，立即更新客户名称
							if (this.detailList.length > 0) {
								this.updateCustomerNames();
							}
						}
					})
					.catch(err => {
						console.error('加载客户列表失败:', err);
					});
			},

			// 新增加载供应商列表的方法
			loadSupplierList() {
				console.log('加载供应商列表...');
				api.listSupplier({ pageNum: 1, pageSize: 1000 })
					.then(res => {
						console.log('供应商列表加载成功，原始数据:', res);
						if (res && res.rows && Array.isArray(res.rows)) {
							// 将供应商数据转为ID-名称映射
							this.supplierMap = {};
							res.rows.forEach(supplier => {
								// 使用API返回的supplierId字段作为键
								if (supplier.supplierId !== undefined) {
									this.supplierMap[supplier.supplierId] = supplier.supplierName || '未命名供应商';
									console.log(`添加供应商映射(supplierId): ID=${supplier.supplierId}, 名称=${supplier.supplierName}`);
								} 
								// 兼容处理，也尝试使用id字段
								else if (supplier.id !== undefined) {
									this.supplierMap[supplier.id] = supplier.supplierName || supplier.name || '未命名供应商';
									console.log(`添加供应商映射(id): ID=${supplier.id}, 名称=${supplier.supplierName || supplier.name}`);
								}
							});
							console.log('供应商映射表建立完成:', this.supplierMap);
							
							// 如果已有详情数据且是进货类型，立即更新供应商名称
							if (this.detailList.length > 0 && this.activeBusinessType === 'purchase') {
								this.updateSupplierNames();
							}
						}
					})
					.catch(err => {
						console.error('加载供应商列表失败:', err);
					});
			},

			// 新增更新客户名称的方法
			updateCustomerNames() {
				this.detailList.forEach(item => {
					if (item.customerId && this.customerMap[item.customerId]) {
						item.customerName = this.customerMap[item.customerId];
					} else if (item.customerId) {
						// 如果找不到对应的客户名称，显示ID+标记
						item.customerName = item.customerId + '(未知客户)';
					} else {
						item.customerName = '零售客户';
					}
				});
			},

			// 新增更新供应商名称的方法
			updateSupplierNames() {
				console.log('开始更新供应商名称...');
				console.log('当前供应商映射表:', this.supplierMap);
				console.log('当前详情列表:', this.detailList);
				
				this.detailList.forEach(item => {
					console.log(`处理明细项: ID=${item.id}, 供应商ID=${item.customerId}`);
					if (item.customerId && this.supplierMap[item.customerId]) {
						// customerId在进货单中实际上是supplierId
						item.customerName = this.supplierMap[item.customerId];
						console.log(`找到匹配的供应商: ${item.customerName}`);
					} else if (item.customerId) {
						// 如果找不到对应的供应商名称，显示ID+标记
						item.customerName = `${item.customerId}(未知供应商)`;
						console.log(`未找到供应商: ${item.customerId}`);
					} else {
						item.customerName = '未指定供应商';
						console.log('未指定供应商ID');
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
page {
	background-color: #F6F6F6;
	min-height: 100%;
	overflow: hidden; /* Prevent body scroll */
}

/* 页面整体布局 */
.detail-page {
	display: flex;
	height: 100vh; /* 视窗高度 */
	position: relative;
	background-color: #F6F6F6;
	/* padding-top: 80rpx; 移除，因为date-tabs是固定的 */
}

/* 左侧业务类型导航 */
.side-nav {
	padding-top: 150rpx; /* 为日期标签留出空间 */
	display: flex;
	flex-direction: column;
	position: fixed;
	left: 0;
	top: 0;
	width: 90rpx;
	height: 100vh; /* Full height relative to viewport */
	z-index: 100;
	background-color: #eef1f8;
	box-sizing: border-box; /* Include padding in height */
	
	.side-nav-item {
		width: 90rpx;
		height: 120rpx;
		margin-bottom: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #FFFFFF;
		font-size: 26rpx;
		line-height: 30rpx;
		text-align: center;
		border-top-right-radius: 20rpx;
		border-bottom-right-radius: 20rpx;
		background-color: #4A8CFF; // Default color (Purchase Blue)
		transition: background-color 0.2s ease;

		&.active {
			background-color: #3ACBC1; // Active color (Sales Green)
			font-weight: bold;
		}
	}
}

/* 顶部日期标签 - 固定 */
.date-tabs {
	position: fixed;
	top: 0; 
	left: 0rpx; /* 避开左侧导航 */
	right: 0;
	height: 80rpx;
	display: flex;
	background-color: #FFFFFF;
	flex-shrink: 0;
	border-bottom: 1rpx solid #F0F0F0;
	z-index: 101;
	
	.date-tab-item {
		flex: 1;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		color: #8A8A8A;
		position: relative;
		
		&.active {
			color: #3ACBC1;
			font-weight: 500;
			
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 60rpx;
				height: 4rpx;
				background-color: #3ACBC1;
				border-radius: 2rpx;
			}
		}
	}
}

/* 内容区域容器 */
.content-area {
	flex: 1;
	margin-left: 90rpx;
	display: flex; 
	flex-direction: column; 
	height: 100vh; /* Full height relative to viewport */
	padding-top: 80rpx; /* Space for fixed date-tabs */
	box-sizing: border-box; /* Include padding in height */
}

/* 主内容区域 */
.main-content {
	display: flex;
	flex-direction: column;
	flex: 1;
	min-height: 0; /* Crucial for flex shrinking */
	overflow: hidden; /* Prevent content overflow */
}

/* 内容面板 */
.content-panel {
	flex: 1;
	margin: 20rpx;
	background-color: #FFFFFF;
	border-radius: 16rpx;
	overflow: hidden;
	display: flex;
	flex-direction: column;
	min-height: 0; /* Crucial for flex shrinking */
}

/* 业务类型标签 */
.business-type-tabs {
	display: flex;
	padding: 20rpx 0;
	flex-shrink: 0; /* Prevent shrinking */
	border-bottom: 1rpx solid #F0F0F0; /* Add separator */
	
	.business-type-tab {
		flex: 1;
		height: 70rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		color: #8A8A8A;
		position: relative;
		
		&.active {
			color: #3ACBC1;
			font-weight: 500;
			
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 60rpx;
				height: 4rpx;
				background-color: #3ACBC1;
				border-radius: 2rpx;
			}
		}
	}
}

/* Placeholder for types without sub-tabs */
.no-sub-tabs-placeholder {
	height: 1rpx; /* Just to occupy space and allow border-top on search-box */
	background-color: #F0F0F0;
	flex-shrink: 0; /* Prevent shrinking */
}

/* 搜索框 */
.search-box {
	padding: 20rpx 30rpx;
	border-top: 1rpx solid #F0F0F0; /* Separator when no tabs */
	flex-shrink: 0; /* Prevent shrinking */
	
	.search-input-wrapper {
		display: flex;
		align-items: center;
		height: 72rpx;
		background-color: #F6F6F6;
		border-radius: 36rpx;
		padding: 0 24rpx;
		
		input {
			flex: 1;
			height: 100%;
			font-size: 26rpx;
			margin: 0 10rpx;
			color: #333333;
		}
		
		.clear-icon {
			padding: 6rpx;
		}
	}
}

/* 日期和合计栏 */
.date-total-bar {
	display: flex;
	align-items: center;
	height: 80rpx;
	padding: 0 30rpx;
	border-top: 1rpx solid #F0F0F0;
	border-bottom: 1rpx solid #F0F0F0;
	flex-shrink: 0; /* Prevent shrinking */
	
	.date-range {
		font-size: 24rpx;
		color: #8A8A8A;
	}
	
	.total-section {
		margin: 0 auto; /* Center align */
		display: flex;
		align-items: center;
		font-size: 24rpx;
		
		.total-label {
			color: #8A8A8A;
		}
		
		.total-amount {
			color: #3ACBC1;
			font-weight: 500;
		}
	}
	
	.add-button {
		width: 48rpx;
		height: 48rpx;
		background-color: #3ACBC1;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
}

/* 明细列表 */
.detail-list-container {
	flex: 1;
	overflow: hidden;
	min-height: 0; /* Already added */
	position: relative; /* Needed for absolute positioning inside if any */
}

.detail-list-scroll {
	position: absolute; /* Use absolute positioning */
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	height: auto; /* Let absolute positioning define height */
	/* height: 100%; Can be problematic with absolute */
	
	.detail-item {
		display: flex;
		align-items: center;
		padding: 24rpx 30rpx;
		border-bottom: 1rpx solid #F0F0F0;
		
		.item-info {
			flex: 1;
		}
		
		.info-line-1, .info-line-2, .info-line-3 {
			display: flex;
			align-items: center;
		}
		
		.info-line-1 {
			justify-content: space-between;
			margin-bottom: 6rpx;
			
			.item-date {
				font-size: 24rpx;
				color: #AEAEAE;
			}
			
			.item-amount {
				font-size: 28rpx;
				color: #333333;
			}
		}
		
		.info-line-2 {
			margin-bottom: 6rpx;
			
			.item-customer {
				font-size: 28rpx;
				color: #333333;
				font-weight: 500;
			}
		}
		
		.info-line-3 {
			.item-code {
				font-size: 24rpx;
				color: #AEAEAE;
			}
		}
		
		.arrow-icon {
			margin-left: 20rpx;
		}
	}
	
	.loadmore-area {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100rpx;
	}
}

/* 空状态 */
.empty-state {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	background-color: #FFFFFF;
	
	.empty-image {
		width: 300rpx;
		height: 300rpx;
		margin-bottom: 40rpx;
	}
	
	.empty-text {
		font-size: 26rpx;
		color: #AEAEAE;
	}
}
</style> 